package com.etl.dataflow.executor.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;

/**
 * @author dx
 * @since 2022/4/14
 */
public class Lob2JavaUtil {

    public static String clobToString(Clob clob) throws SQLException, IOException {
        if (clob == null) {
            return null;
        }
        String reString;
        Reader is = clob.getCharacterStream();
        BufferedReader br = new BufferedReader(is);
        String s = br.readLine();
        StringBuilder sb = new StringBuilder();
        while (s != null) {
            sb.append(s).append("\n");
            s = br.readLine();
        }
        reString = sb.toString();
        return reString;
    }

    public static byte[] blobToBytes(Blob blob) {
        if (blob == null) {
            return null;
        }
        try (BufferedInputStream is = new BufferedInputStream(blob.getBinaryStream())) {
            byte[] bytes = new byte[(int) blob.length()];
            int len = bytes.length;
            int offset = 0;
            int read;
            while (offset < len
                    && (read = is.read(bytes, offset, len - offset)) >= 0) {
                offset += read;
            }
            return bytes;
        } catch (Exception ignored) {
            return null;
        }
    }

}
